package com.yfbao.encryptor;

import com.yfbao.config.FieldEncrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.stream.Collectors;

@Component
public class QueryConditionEncryptor {

    @Autowired
    private AESEncryptor encryptor;

    /**
     * 加密查询条件
     */
    public Object encryptCondition(Object condition) {
        if (condition == null) {
            return null;
        }

        if (condition instanceof String) {
            return encryptor.encrypt((String) condition);
        } else if (condition instanceof Collection) {
            // 处理IN查询的条件列表
            return ((Collection<?>) condition).stream()
                    .map(item -> item instanceof String ? encryptor.encrypt((String) item) : item)
                    .collect(Collectors.toList());
        } else if (condition.getClass().isArray()) {
            // 处理数组条件
            Object[] array = (Object[]) condition;
            Object[] encryptedArray = new Object[array.length];
            for (int i = 0; i < array.length; i++) {
                if (array[i] instanceof String) {
                    encryptedArray[i] = encryptor.encrypt((String) array[i]);
                } else {
                    encryptedArray[i] = array[i];
                }
            }
            return encryptedArray;
        }

        return condition;
    }

    /**
     * 判断字段是否需要加密查询
     */
    public boolean needEncryptQuery(String columnName, Class<?> entityClass) {
        try {
            Field field = getField(entityClass, columnName);
            return field != null && field.isAnnotationPresent(FieldEncrypt.class);
        } catch (Exception e) {
            return false;
        }
    }

    private Field getField(Class<?> clazz, String fieldName) {
        while (clazz != null && clazz != Object.class) {
            try {
                return clazz.getDeclaredField(fieldName);
            } catch (NoSuchFieldException e) {
                clazz = clazz.getSuperclass();
            }
        }
        return null;
    }

    /**
     * 转换数据库列名为字段名
     */
    public String columnToFieldName(String columnName) {
        // 下划线转驼峰
        if (columnName.contains("_")) {
            StringBuilder result = new StringBuilder();
            String[] parts = columnName.split("_");
            for (int i = 0; i < parts.length; i++) {
                if (i == 0) {
                    result.append(parts[i]);
                } else {
                    result.append(parts[i].substring(0, 1).toUpperCase())
                            .append(parts[i].substring(1));
                }
            }
            return result.toString();
        }
        return columnName;
    }
}
